package com.lrm.web.admin;

import com.lrm.po.User;
import com.lrm.service.UserService;
import com.lrm.util.MD5Utils;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by limi on 2017/10/15.
 */
@Controller
@RequestMapping("/admin")
public class LoginController {


    @Autowired
    private UserService userService;

    @GetMapping
    public String loginPage() {
        return "admin/login";
    }


    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
        User user = userService.checkUser(username);
        if (user == null) {
            attributes.addFlashAttribute("message", "用户不存在");
            return "redirect:/admin";
        }
        if (!user.getPassword().equals(MD5Utils.code(password))) {
            attributes.addFlashAttribute("message", "密码错误");
            return "redirect:/admin";
        }
        user.setPassword(null);
        session.setAttribute("user", user);
        return "admin/index";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }

    @GetMapping("/qqLogin")
    public ResponseEntity<Void> qqLogin(HttpServletRequest request, HttpServletResponse response,
                                        RedirectAttributes attributes) {
        response.setContentType("text/html,charset=utf-8");
        try {
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
            return ResponseEntity.ok().build();
        } catch (IOException | QQConnectException e) {
            attributes.addFlashAttribute("message", "用户名和密码错误");
        }
        return ResponseEntity.badRequest().build();
    }

    @RequestMapping("/callback")
    public String callback(HttpServletRequest request, HttpSession session, RedirectAttributes attributes) {
        try {
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
            //用来或用户信息，get_user_info参数
            if ("".equals(accessTokenObj.getAccessToken())) {
                attributes.addFlashAttribute("message", "用户名或密码错误");
                return "redirect:/admin";
            }
            String accessToken = accessTokenObj.getAccessToken();
            // 利用获取到的accessToken 去获取当前用的openid -------- start
            String openId = new OpenID(accessToken).getUserOpenID();
            System.out.println(openId);
            User user = userService.getUser(openId);
            if (ObjectUtils.isEmpty(user)) {
                attributes.addFlashAttribute("message", "QQ登录用户无效，请使用其他方式登录");
                return "redirect:/admin";
            }
            user.setPassword(null);
            session.setAttribute("user", user);
            return "admin/index";

        } catch (QQConnectException e) {
            attributes.addFlashAttribute("message", "qq连接发生异常"+e.getMessage());
            return "redirect:/admin";
        }
    }
}
